package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    //微信请求地址。
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    /**
     * 用户登录
     * @return
     */
    @Override
    public User userLogin(UserLoginDTO userLoginDTO) {
        //获取openId
        String openId = this.getOpenId(userLoginDTO.getCode());
        //根据openID查询数据库中的用户对象。
        User user = userMapper.selectUserByOpenId(openId);
        //判断用户对象是否为空，如果为空的话就直接创建对象，并插入数据中，返回需要的主键ID
        if (user ==null){
            user = User.builder().openid(openId).createTime(LocalDateTime.now()).build();
            userMapper.insertUser(user);//后绪步骤实现
        }
        //将用户对象返回。
        return user;
    }

    private String getOpenId(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;

    }
}
